/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301,  USA
 */

/**
 * @version log.c 0.0.1
 * @package Comoro
 * @author Dr.NP <np@group.org>
 * 
 * Record general log file
 */

#include "bspd.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#include <pthread.h>

extern struct conf setting;
int log_fd;
char tmp[MAX_LOG_LINE_LENGTH], line[MAX_LOG_LINE_LENGTH];
static pthread_mutex_t log_mutex;

/* Init log operator */
int log_init(char *log_file)
{
	if (log_file)
	{
		log_fd = open(log_file, O_WRONLY|O_CREAT|O_APPEND, S_IRWXU);
	}

	else
	{
		log_fd = open(setting.log_filename, O_WRONLY|O_CREAT|O_APPEND, S_IRWXU);
	}
	
	if (log_fd <= STDERR_FILENO)
	{
		close(log_fd);
		log_fd = 0;

		fprintf(stderr, "Log file open error, maybe locked by other process\n");

		exit(EXIT_IO_ERROR);
	}
	
	flock(log_fd, LOCK_EX);

	fprintf(stderr, "Logger initialized\n");
	
	return RTN_SUCCESS;
}

/* Write one line into log */
int log_add(char *log_msg, ...)
{
	va_list ap;
	va_start(ap, log_msg);
	vsprintf(tmp, log_msg, ap);
	va_end(ap);
	
	time_t timep;
	struct tm *t;
	
	time(&timep);
	t = localtime(&timep);
	
	int ret = 0;
	
	if (log_fd > STDERR_FILENO)
	{
		pthread_mutex_lock(&log_mutex);
		
		sprintf(line, "[%02d/%02d/%04d %02d:%02d:%02d] : %s\n", t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, t->tm_hour, t->tm_min, t->tm_sec, tmp);
		ret = write(log_fd, line, strlen(line));

		pthread_mutex_unlock(&log_mutex);
	}
	
	return ret;
}

/* Close log file, sync data */
int log_close()
{
	flock(log_fd, LOCK_UN);
	fsync(log_fd);
	close(log_fd);
	
	return RTN_SUCCESS;
}
